package com.soxing.webrain.brush.common.util;

import java.util.Arrays;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

public class AddressDesUtil {
    /**
     *
     * secret key
     *
     */
    private static Key key;
    private static String KEY_STR = "myKeyKKK";
    static {
        try {
            /*linux*/
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes());

            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(secureRandom);
            key = keyGenerator.generateKey();
            keyGenerator = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     *
     * Encrypt
     *   将库换成了import java.util.Base64.Encoder;
     */
    public static String getEncryptString(String string) {
        Encoder encoder = Base64.getEncoder();
        try {
            byte[] strBytes = string.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return encoder.encodeToString(encryptStrBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public static String getEncryptString(String hh) {
//        // BASE64Encoder encoder = new BASE64Encoder();
//        // String encode = encoder.encode(data);
//        // 从JKD 9开始rt.jar包已废除，从JDK 1.8开始使用java.util.Base64.Encoder
//
//        byte[] data =
//        Encoder encoder = Base64.getEncoder();
//        String encode = encoder.encodeToString(data);
//        return encode;
//    }

    /**
     *
     * Decrypt
     *
     */
    public static String getDecryptString(String str) {
        Decoder decoder = Base64.getDecoder();
        try {
            byte[] strBytes = decoder.decode(str);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE,key);
            byte[] decryptStrBytes = cipher.doFinal(strBytes);
            return new String(decryptStrBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
